﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using KaytechSoftware.Cms.Entities;
using KaytechSoftware.Cms.Entities.Interfaces;
using KaytechSoftware.Cms.Services.Dto;
using KaytechSoftware.Cms.Services.Interfaces;
using KaytechSoftware.Cms.Services.Interfaces.Entity;

namespace KaytechSoftware.Cms.Services.Services.Entity
{
    public class PhotoAlbumService : OrderedEntityBaseService<PhotoAlbum, PhotoAlbumDto>, IPhotoAlbumService
    {
        private readonly IRepository<Page> _pageRepository;

        public PhotoAlbumService(IUnitOfWorkService unitOfWorkService, IRepository<PhotoAlbum> photoAlbumRepository, IRepository<Page> pageRepository) : base(unitOfWorkService, photoAlbumRepository)
        {
            _pageRepository = pageRepository;
        }

        public override void Save(PhotoAlbumDto dto)
        {
            using (var unitOfWork = UnitOfWorkService.Create())
            {
                var photoAlbum = GetInstance(dto.Id);
                photoAlbum.Title = dto.Title;
                photoAlbum.Description = dto.Description;
                photoAlbum.Order = 1;
                photoAlbum.Page = _pageRepository.GetById(dto.PageId);

                Store(photoAlbum);
                unitOfWork.Commit();
            }
        }

        public override IList<PhotoAlbumDto> GetAll()
        {
            using (UnitOfWorkService.Create())
            {
                var albums = EntityRepository.GetAll(a => a.Page).ToList();
                return albums.Select(a => new PhotoAlbumDto(a)).ToList();
            }
        }

        public IList<PhotoAlbumDto> GetAllForPage(long pageId)
        {
            using (UnitOfWorkService.Create())
            {
                var albums = EntityRepository.GetAll(new Expression<Func<PhotoAlbum, object>>[] {a => a.Page, a => a.MainPhoto}).Where(a => a.Page.Id == pageId).OrderByDescending(a => a.Order).ToList();
                return albums.Select(a => new PhotoAlbumDto(a)).ToList();
            }
        }

        protected override IQueryable<PhotoAlbum> LimitEntitiesForOrdering(PhotoAlbum promotedEntity)
        {
            return EntityRepository.GetAll().Where(a => a.PageId == promotedEntity.PageId);
        }
    }
}
